---
import { buildUrl } from '@utils/url-builder';
import { getCollection } from 'astro:content';
import { getItemsFromCollectionByIdAndSemverOrLatest } from '@utils/collections/util';
import PillListFlat from './PillListFlat';
import { resourceToCollectionMap } from '@utils/collections/util';
interface Props {
  section?: {
    title?: string;
    limit?: number;
    items: {
      id: string;
      type: string;
      version?: string;
    }[];
  };
}

const { section } = Astro.props;
const title = section?.title || 'Custom Section';
const limit = section?.limit || 10;
const sectionItems = section?.items || [];

// Array to store resolved related resources
const resolvedResources = [];

// Fetch related resources
for (const resource of sectionItems) {
  try {
    // Use type assertion to ensure TypeScript understands this is a valid collection name
    const collectionName = resourceToCollectionMap[resource.type as keyof typeof resourceToCollectionMap];

    // Use getEntry instead of getCollection for single item lookup by ID
    const allItemsInCollection = await getCollection(collectionName);
    // @ts-ignore
    const entryToMatchVersion = getItemsFromCollectionByIdAndSemverOrLatest(allItemsInCollection, resource.id, resource.version);
    const entry = entryToMatchVersion[0];

    if (entry) {
      resolvedResources.push(entry);
    }
  } catch (error) {
    console.error(`Failed to fetch related resource: ${resource.id} of type ${resource.type}`, error);
  }
}

const sectionList = resolvedResources.map((p: any) => ({
  label: `${p.data.name}`,
  tag: `v${p.data.version}`,
  collection: p.collection,
  href: buildUrl(`/docs/${p.collection}/${p.data.id}/${p.data.version}`),
}));
---

<PillListFlat title={`${title} (${sectionList.length})`} pills={sectionList} color="orange" limit={limit} client:load />
